package com.cyf.plc

import android.content.Context
import android.content.ContextWrapper
import androidx.multidex.MultiDex
import com.cyf.library.thread.ThreadManager
import com.cyf.plc.di.component.DaggerAppComponent
import com.cyf.plc.handler.CrashHandler
import com.cyf.plc.plc.PlcExecutor
import com.cyf.plc.util.AppUtils.getCurrentProcessName
import com.pixplicity.easyprefs.library.Prefs
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.HasAndroidInjector
import io.github.inflationx.calligraphy3.CalligraphyConfig
import io.github.inflationx.calligraphy3.CalligraphyInterceptor
import io.github.inflationx.viewpump.ViewPump
import kotlinx.coroutines.ExperimentalCoroutinesApi
import javax.inject.Inject

@ExperimentalCoroutinesApi
class PlcApp : BaseApp(), HasAndroidInjector {

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        MultiDex.install(this)
    }

    @Inject
    lateinit var androidInjector: DispatchingAndroidInjector<Any>

    override fun onCreate() {
        super.onCreate()
        //@author 海航 防止多进程导致多次初始化
        if (packageName == getCurrentProcessName(this)) {
            initApp()
        }
    }

    private fun initApp() {
        //设置记录崩溃日志
//        Thread.setDefaultUncaughtExceptionHandler(CrashHandler(this));

        //ViewPump 使用自定义字体
        ViewPump.init(
            ViewPump.builder()
                .addInterceptor(
                    CalligraphyInterceptor(
                        CalligraphyConfig.Builder()
                            .setDefaultFontPath("fonts/fontzipMin.ttf")
                            .setFontAttrId(R.attr.fontPath)
                            .build()
                    )
                )
                .build()
        )
        //print thread info 打印线程信息
        ThreadManager.printThreadExecutorInfo()
        // Initialize Dependency Injection 初始化依赖注入
        DaggerAppComponent.builder()
            .create(this)
            .build()
            .inject(this)
        // Initialize the Prefs class 初始化Prefs
        Prefs.Builder()
            .setContext(this)
            .setMode(ContextWrapper.MODE_PRIVATE)
            .setPrefsName(packageName)
            .setUseDefaultSharedPreference(true)
            .build()
        //初始化 plc读取线程
        PlcExecutor.initPlc(PlcExecutor.getPlcIp(), 0, 3020)
    }

    override fun androidInjector(): AndroidInjector<Any> {
        return androidInjector
    }

}